package com.whfc.iot.fse.crane.util;

import com.whfc.common.util.JSONUtil;
import com.whfc.iot.fse.crane.codec.TwMsgDataCodec;
import com.whfc.iot.fse.crane.codec.TwMsgDecoderFactory;
import com.whfc.iot.fse.crane.entity.TwMsg;
import com.whfc.iot.fse.crane.entity.TwMsgFactory;
import com.whfc.iot.fse.lift.codec.LiftMsgDataCodec;
import com.whfc.iot.fse.lift.codec.LiftMsgDataDecoderFactory;
import com.whfc.iot.fse.lift.entity.LiftMsg;
import com.whfc.iot.fse.lift.entity.LiftMsgFactory;
import com.whfc.iot.util.ByteUtil;
import io.netty.buffer.ByteBuf;

/**
 * @Description: 塔吊数据编解码工具
 * @author: xugcheng
 * @version: 1.0
 * @date: 2021-05-19 11:53
 */
public class TwMsgUtil {

    /**
     * 编码
     *
     * @param msg
     * @return
     */
    public static String encode(TwMsg msg) {
        return JSONUtil.toString(msg);
    }

    /**
     * 解码
     *
     * @param buf
     * @return
     */
    public static TwMsg decode(ByteBuf buf) {
        //跳过帧头
        buf.skipBytes(2);

        //数据类型
        int dataType = buf.readUnsignedByte();

        //塔吊编号
        int cage = buf.readUnsignedByte();
        int cageNo = cage >> 1;

        //硬件SN(设备编号)
        byte[] deviceSnBytes = new byte[3];
        buf.readBytes(deviceSnBytes);
        int deviceSn = ByteUtil.low3ByteToInt(deviceSnBytes);

        //数据
        TwMsg msg = TwMsgFactory.createTwMsg(dataType);
        TwMsgDataCodec twMsgDataCodec = TwMsgDecoderFactory.getTwMsgDataCodec(dataType);
        twMsgDataCodec.decode(buf, msg);

        //校验值
        int checkSum = buf.readByte();

        //长度
        int length = buf.readUnsignedByte();

        //帧尾
        buf.skipBytes(4);

        msg.setDataType(dataType);
        msg.setCageNo(cageNo);
        msg.setDeviceSn(deviceSn);
        msg.setCheckSum(checkSum);
        msg.setLength(length);
        return msg;
    }
}
